package com.martin.lib_base.helper

import com.flyjingfish.android_aop_annotation.anno.AndroidAopCollectMethod
import com.martin.lib_base.interfaces.IAppLifeListener
import com.martin.lib_base.interfaces.IHeartAutoListener
import dev.utils.common.ReflectUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

/**
 * 心跳助手
 */
object HeartHelper : IAppLifeListener {

    // 心跳计数
    private var count = 0L

    // 心跳监听类
    private val autoListenerList = ArrayList<IHeartAutoListener>()

    // 心跳回调
    private val callBackList = ArrayList<() -> Unit>()

    private var job: Job? = null

    // 应用启动时开始发送心跳
    override fun onAppCreate() {
        showLog("启动心跳")
        job?.cancel()
        job = flow {
            while (true) {
                count++
                emit(count)
            }
        }
            .onEach { delay(1000) }
            .flowOn(Dispatchers.IO)
            .onEach {
                showLog("发送心跳 onEach $it")
                callBackList.forEach { callBack ->
                    callBack.invoke()
                }
                autoListenerList.forEach { listener ->
                    listener.onHeart()
                }
            }
            .flowOn(Dispatchers.Main)
            .launchIn(GlobalScope)
    }

    /**
     * 收集自动监听类
     * 自动调用,禁止手动调用
     */
    @AndroidAopCollectMethod
    @JvmStatic
    fun collectAutoListener(bean: IHeartAutoListener) {
        if (!AppLifecycleHelper.isMainProcess()) return
        showLog("收集 IHeartAutoListener ===== ${bean.javaClass.simpleName} ===== ${bean.hashCode()}")
        autoListenerList.add(bean)
    }

    /**
     * 获取自动监听类
     */
    fun getAutoListener(clazz: Class<out IHeartAutoListener>): IHeartAutoListener {
        var find = autoListenerList.find { it.javaClass == clazz }
        if (find == null) {
            find = ReflectUtils.reflect(clazz).newInstance().get()
            autoListenerList.add(find!!)
        }
        return find
    }

    /**
     * 添加回调
     */
    fun registerCallBack(callBack: () -> Unit) {
        callBackList.add(callBack)
    }

    /**
     * 移除回调
     */
    fun unRegisterCallBack(callBack: () -> Unit) {
        callBackList.remove(callBack)
    }

    private fun showLog(log: String) {
//        loge("心跳工具类 : $log")
    }
}